<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-button type="primary" @click="addUser">添加角色</el-button>
      <!-- 表格区域 -->
      <el-table :data="roles" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一行一级权限 -->
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              class="borderBot"
              :class="index === 0 ? 'borderTop' : ''"
            >
              <!-- 渲染一级权限的名字 -->
              <el-col :span="5">
                <el-tag closable @close="removeTag(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 嵌套二级 -->
              <el-col :span="19">
                <el-row
                  v-for="(item1, index1) in item.children"
                  :key="item1.id"
                  :class="index1 !== 0 ? 'borderTop' : ''"
                >
                  <!-- 渲染二级权限的名字 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeTag(scope.row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 嵌套三级 -->
                  <el-col :span="18">
                    <!-- 渲染三级权限的名字 -->
                    <el-tag
                      closable
                      @close="removeTag(scope.row, item2.id)"
                      type="warning"
                      v-for="item2 in item1.children"
                      :key="item2.id"
                    >
                      {{ item2.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="clickDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showSetRights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑按钮对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="30%">
      <el-form
        ref="editUserFrom"
        :model="editUser"
        label-width="80px"
        :rules="editRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editUser.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editUser.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editClickUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配用户权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
    >
      <el-tree
        :data="rights"
        node-key="id"
        :props="defaultProps"
        show-checkbox
        ref="tree"
        default-expand-all
        :default-checked-keys="defaultKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
      <el-form
        :model="addForm"
        label-width="80px"
        :rules="addRules"
        ref="addFromRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClickRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      roles: [],
      // 编辑角色对话框的显示和隐藏
      editDialogVisible: false,
      editUser: {},
      // 修改角色的验证规则
      editRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 分配权限对话框的显示与隐藏
      setRightsDialogVisible: false,
      rights: [],
      defaultProps: {
        childred: 'children',
        label: 'authName'
      },
      defaultKeys: [],
      roleId: null,
      // 添加角色对话框
      addDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getRoles()
  },

  methods: {
    // 获取数据
    async getRoles () {
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.roles = res.data
    },
    // 移除tag标签的事件
    removeTag (row, rightsId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`roles/${row.id}/rights/${rightsId}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功!')
        row.children = res.data
        console.log(res.data)
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 编辑按钮
    editRole (row) {
      this.editDialogVisible = true
      this.editUser = JSON.parse(JSON.stringify(row))
    },
    // 点击了编辑按钮
    editClickUser () {
      // 验证表单是否符合规则
      this.$refs.editUserFrom.validate(async flag => {
        if (!flag) return
        // 把最新的数据赋值到editUser
        const { id, roleName, roleDesc } = this.editUser
        console.log(id, roleName, roleDesc)
        // 发送请求
        const { data: res } = await this.$axios.put('roles/' + id, {
          roleName,
          roleDesc
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.editDialogVisible = false
        this.getRoles()
        this.$message.success('修改成功')
      })
    },
    // 删除按钮
    clickDelete (row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('roles/' + row.id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getRoles()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 分配权限按钮
    async showSetRights (row) {
      this.setRightsDialogVisible = true
      this.roleId = row.id
      // 获得数据
      const { data: res } = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rights = res.data
      this.defaultKeys = []
      this.getAllKeys(row)
      this.setRightsDialogVisible = true
    },
    // 利用递归函数, 获得三级分类数据
    getAllKeys (row) {
      if (!row.children) {
        return this.defaultKeys.push(row.id)
      }
      row.children.forEach(item => {
        this.getAllKeys(item)
      })
    },
    async setRights () {
      // 1.角色id
      // 2.分配的权限id 选中的树形的阶段
      // getCheckedKeys 获取全选的id
      // getHalfCheckedKeys 获取半选的id
      const id = this.roleId
      const rids = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()].join(',')
      const { data: res } = await this.$axios.post(`roles/${id}/rights`, { rids })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.setRightsDialogVisible = false
      this.getRoles()
    },
    // 点击了添加角色按钮
    addUser () {
      this.addDialogVisible = true
    },
    addClickRole () {
      this.$refs.addFromRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('roles', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.addDialogVisible = false
        this.getRoles()
        this.$message.success('添加用户成功')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.borderTop {
  border-top: 1px solid #ccc;
}
.borderBot {
  border-bottom: 1px solid #ccc;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>
